import axios from 'axios'
import { useUserStore } from '@/stores/user'
import { useAdminStore } from '@/stores/admin'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { jwtDecode } from 'jwt-decode'

const request = axios.create({
  baseURL: 'http://localhost:3000/api',
  timeout: 15000
})

// 检查 token 是否过期
const checkTokenExpiration = () => {
  try {
    const userStore = useUserStore()
    const adminStore = useAdminStore()

    // 检查用户 token
    if (userStore.token) {
      const userDecodedToken = jwtDecode(userStore.token)
      if (userDecodedToken.exp * 1000 < Date.now()) {
        handleTokenExpired('/users')
      }
    }

    // 检查管理员 token
    if (adminStore.token) {
      const adminDecodedToken = jwtDecode(adminStore.token)
      if (adminDecodedToken.exp * 1000 < Date.now()) {
        handleTokenExpired('/admin')
      }
    }
  } catch (error) {
    console.error('Token check error:', error)
  }
}

// 启动定时检查
checkTokenExpiration() // 立即检查一次
setInterval(checkTokenExpiration, 30000) // 每30秒检查一次

// 请求拦截器：携带 token
request.interceptors.request.use(
  config => {
    const isAdminRoute = config.url.startsWith('/admin') || 
                        config.url.includes('/admin/') ||
                        config.url.startsWith('/statistics')
    const store = isAdminRoute ? useAdminStore() : useUserStore()
    
    if (store.token) {
      config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  }
)

// 响应拦截器：处理 token 过期
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 判断是否是管理员路由
    const isAdminRoute = error.config.url.startsWith('/admin') || 
                        error.config.url.startsWith('/statistics')

    if (error.response?.status === 401 || 
        error.response?.data?.code === 401 || 
        error.message.includes('登录已过期')) {
      // 清除登录状态
      if (isAdminRoute) {
        const adminStore = useAdminStore()
        adminStore.clearAdminInfo()
        router.push('/admin/login')
      } else {
        const userStore = useUserStore()
        userStore.clearUserInfo()
        router.push('/user/login')
      }

      ElMessage.error('登录已过期，请重新登录')
    }
    return Promise.reject(error)
  }
)

// 统一处理 token 过期
const handleTokenExpired = (url) => {
  const isAdminRoute = url.startsWith('/admin')
  
  if (isAdminRoute) {
    const adminStore = useAdminStore()
    adminStore.clearAdminInfo()
    router.push('/admin/login')
  } else {
    const userStore = useUserStore()
    userStore.clearUserInfo()
    router.push('/user/login')
  }
  
  ElMessage.warning('登录已过期，请重新登录')
}

export default request 